package loan.calc.listener;

import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.Constants;
import org.springdoc.core.SwaggerUiConfigProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;


@Component
@ConditionalOnWebApplication
@Slf4j
public class ApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        Environment env = applicationContext.getEnvironment();
        String jvmName = ManagementFactory.getRuntimeMXBean().getName();
        String ip;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            ip = "127.0.0.1";
        }
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        if (!StringUtils.hasText(path)) {
            path = "";
        }
        String applicationName = env.getProperty("spring.application.name");

        SwaggerUiConfigProperties swaggerUiConfigProperties = applicationContext.getBean(SwaggerUiConfigProperties.class);
        boolean swaggerUiConfigPropertiesEnabled = swaggerUiConfigProperties.isEnabled();
        String swaggerUiConfigPropertiesPath = StringUtils.hasText(swaggerUiConfigProperties.getPath()) ? swaggerUiConfigProperties.getPath() : Constants.DEFAULT_SWAGGER_UI_PATH;
        log.info("\n" +
                "\t----------------------------------------------------------\n" +
                "\tApplication[" + applicationName + "] is running! \n" +
                "\tApplication[" + applicationName + "] Process ID: " + jvmName.split("@")[0] + "\n" +
                "\tApplication[" + applicationName + "] Access URLs:\n" +
                "\t\tLocal: \t\thttp://localhost:" + port + path + "\n" +
                "\t\tNetwork: \thttp://" + ip + ":" + port + path + "\n" +
                (Boolean.TRUE.equals(swaggerUiConfigPropertiesEnabled) ? "\t\tSwaggerUI(Local): \t\thttp://localhost:" + port + path + swaggerUiConfigPropertiesPath + "\n" : "") +
                (Boolean.TRUE.equals(swaggerUiConfigPropertiesEnabled) ? "\t\tSwaggerUI(Network): \thttp://" + ip + ":" + port + path + swaggerUiConfigPropertiesPath + "\n" : "") +
                "\t----------------------------------------------------------\n");
    }
}
